package com.lx.sync.consumer.service.impl;

import com.lx.sync.common.util.CacheUtil;
import com.lx.sync.core.model.SyncState;
import com.lx.sync.core.service.SyncStateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 组合实现的同步状态服务
 * 同时使用Redis和数据库存储
 */
@Slf4j
@Service
public class CompositeSyncStateServiceImpl implements SyncStateService {

    private static final String SYNC_STATE_KEY_PREFIX = "sync:state:";
    private static final int CACHE_EXPIRE_DAYS = 7;

    @Autowired
    private CacheUtil cacheUtil;

    @Autowired
    private DatabaseSyncStateServiceImpl databaseSyncStateService;

    @Override
    public SyncState getLatestSyncState(String idxName) {
//        String key = SYNC_STATE_KEY_PREFIX + idxName;

        // 1. 先从Redis获取
        SyncState state = null;
//        if (state != null) {
//            return state;
//        }

        // 2. Redis没有，从数据库获取
        try {
            state = databaseSyncStateService.getLatestSyncState(idxName);
            if (state != null) {
                // 3. 同步到Redis
//                cacheUtil.set(key, state, CACHE_EXPIRE_DAYS, TimeUnit.DAYS);
                return state;
            }
        } catch (Exception e) {
            log.error("从数据库获取同步状态失败", e);
        }

        return null;
    }

    @Override
    public boolean saveSyncState(SyncState syncState) {
        String key = SYNC_STATE_KEY_PREFIX + syncState.getIdxName();

        try {
            // 1. 保存到数据库
            boolean dbResult = databaseSyncStateService.saveSyncState(syncState);

            // 2. 保存到Redis
            cacheUtil.set(key, syncState, CACHE_EXPIRE_DAYS, TimeUnit.DAYS);

            return dbResult;
        } catch (Exception e) {
            log.error("保存同步状态失败", e);
            return false;
        }
    }

    @Override
    public boolean updateSyncState(SyncState syncState) {
        String key = SYNC_STATE_KEY_PREFIX + syncState.getIdxName();

        try {
            // 1. 保存到数据库
            boolean dbResult = databaseSyncStateService.updateSyncState(syncState);

            // 2. 保存到Redis
            cacheUtil.set(key, syncState, CACHE_EXPIRE_DAYS, TimeUnit.DAYS);

            return dbResult;
        } catch (Exception e) {
            log.error("保存同步状态失败", e);
            return false;
        }
    }
}
